package server;

import tcpchat02.CloseUtil;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

/**
 * 封装响应信息
 */
public class Response {
    //存储头信息
    private StringBuilder headInfo;
    //存储正文长度
    private int len=0;
    //正文
    private StringBuilder content;
    //流
    private BufferedWriter bw;
    public static final String CRLF="\r\n";
    public static final String BLANK=" ";
    public Response(){
        this.headInfo=new StringBuilder();
        this.content=new StringBuilder();
        this.len=0;

    }
    public Response(OutputStream os){
        this();
        bw=new BufferedWriter(new OutputStreamWriter(os));

    }

    /**
     * 构建正文
     * @return
     */
    public Response print(String info){
        content.append(info);
        len+=info.getBytes().length;
        return this;
    }
    /**
     * 构建正文+回车
     * @return
     */
    public Response println(String info){
        content.append(info).append(CRLF);
        len+=(info+CRLF).getBytes().length;
        return this;
    }
    /**
     * 构建响应头
     */
    private void createHeadInfo(int code){

        headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
        switch(code){
            case 200:
                headInfo.append("OK");
                break;
            case 404:
                headInfo.append("NOT FOUND");
                break;
            case 505:
                headInfo.append("SERVER ERROR");
                break;
        }
        headInfo.append(CRLF);
        headInfo.append("Server:lqk Server/0.0.1").append(CRLF);
        headInfo.append("Date:").append(new Date()).append(CRLF);
        headInfo.append("Content-type:text/html;charset=UTF-8").append(CRLF);
        headInfo.append("Content-Length:").append(len).append(CRLF);
        headInfo.append(CRLF);//分隔符
    }
    //推送到客户端
    void pushToClient(int code){
        createHeadInfo(code);
        try {
            //头信息+分隔符
            bw.append(headInfo.toString());
            //正文
            bw.append(content.toString());
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void close(){
        CloseUtil.closeAll(bw);
    }
}
